import axios from 'axios'
import { message } from 'antd'

import { store } from '@/store/store'
import { logout } from '@/store/actions/login'
import { customHistory } from './history'

export const request = axios.create({
  baseURL: 'http://geek.itheima.net/v1_0',
  timeout: 5000
})

// 请求拦截器
request.interceptors.request.use(config => {
  // console.log('config', config)
  // 获取token
  const token = store.getState().login
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

// 响应拦截器
request.interceptors.response.use(undefined, error => {
  // 通过分析error对象，这个网络超时错误
  if (!error.response) {
    message.error('网络超时，请稍后再试')
    // 交还给axios
    return Promise.reject(error)
  }

  // 和api确定token实效的status
  // if (error.response.status === 401) {
  //   message.warn('token 认证失败，请刷新浏览器后，重新登录');
  //   store.dispatch(logout());
  //   // 交还给axios
  //   return Promise.reject(error);
  // }

  if (error.response.status === 401) {
    // 清理token
    store.dispatch(logout())

    message.warn('token 认证失败', 1, () => {
      // 跳转
      customHistory.push('/login', {
        from: customHistory.location.pathname
      })

      // 交还给axios
      return Promise.reject(error)
    })
  }
})
